<script setup lang="ts">
import type {
  goodsListType,
  goodsData,
  commentDataType,
  commentListType,
  goodsFormType,
} from "../goods-manage/type";
import request from "@/utils/request";
import { ref, onMounted, reactive, onActivated, onDeactivated } from "vue";
import time from "@/utils/time";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import worksList from "@/components/worksList/worksList.vue";
import { newsType } from "./type";
import { previewDataType } from "../news-manage/type";
import { Search } from "@element-plus/icons-vue";
import { Top, Refresh, View, Hide } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import storeWs from "@/utils/store-ws";
const router = useRouter();
const searchShow = ref(true);

onActivated(() => {
  // 组件被 <keep-alive> 缓存后重新激活时执行
  console.log("ComponentA activated");
});

onDeactivated(() => {
  // 组件被 <keep-alive> 缓存前停用时执行
  console.log("ComponentA deactivated");
});

//搜索
const visible = ref(false);
const searchText = ref("");
const searchData = ref([]);

//搜索内容
const searchList = () => {
  if (searchText.value == "") {
    ElMessage({
      message: "请输入搜索内容.",
      type: "warning",
    });
  } else {
    request.get(`/goods/search/${searchText.value}`).then((res) => {
      searchData.value = res.data;
    });
    searchShow.value = false;
  }
};

// 返回
const goBack = () => {
  searchShow.value = true;
  searchText.value = "";
};

// 轮播图开关
const carouselShow = ref(false);
const carouselSwitch = () => {
  carouselShow.value = !carouselShow.value;
};

const store = useStore();
const tableData = ref<goodsData[]>([]);
const newsVisible = ref(false);

const goodsFrom = reactive<goodsFormType>({
  username: "",
  times: "",
  avatar: "",
  name: "",
  content: "",
  category: "",
  imageList: "",
});
const commentData = reactive<commentDataType>({
  times: new Date(),
  goodsId: "",
  username: store.state.userInfo.username,
  comment: "",
  name: store.state.userInfo.name,
  avatar: store.state.userInfo.avatar,
});
const commentValue = ref<string>("");
const commentList = ref<commentDataType[]>([]);
const dialogTableVisible = ref<boolean>(false);
const getTableData = async () => {
  const res: goodsListType = await request.get("/goods/list");

  tableData.value = res.data;
};

const newsList = ref<newsType[]>([]);
const getNewsList = async () => {
  const res = await request.get("/news/homeList");
  newsList.value = res.data;
};

// 预览回调
const previewData = reactive<previewDataType>({
  id: "",
  cover: "",
  username: "",
  name: "",
  isShow: "",
  times: "",
  content: "",
  title: "",
});
const newsPreview = (data: any) => {
  Object.assign(previewData, data);
  newsVisible.value = true;
};

onMounted(() => {
  getTableData();
  getNewsList();
});

const handlePreview = async (data: goodsData) => {
  commentData.goodsId = data.id;
  Object.assign(goodsFrom, data);
  goodsFrom.imageList = JSON.parse(data.imageList).map(
    (url: string) => "http://localhost:3000/" + url
  );
  dialogTableVisible.value = true;
  const res = await request.get(`/goods/commentList/${commentData.goodsId}`);
  commentList.value = res.data;
};
const commentPost = async () => {
  commentData.comment = commentValue.value;
  const res = await request.post<any, commentListType>("/goods/comment", commentData);
  if (res.code == "200") {
    commentList.value.unshift(commentData);
    commentValue.value = "";
  }
};
// 打开聊天窗口
const createChat = (username: any, name: any, avatar: any) => {
  storeWs.publish(username, name, avatar);
  store.commit("changeisShow", true);
};
</script>

<template>
  <div class="search">
    <el-input
      v-model="searchText"
      placeholder="请输入搜索内容..."
      :prefix-icon="Search"
      type="search"
      size="large"
      @click="visible = true"
      @blur="visible = false"
      @keydown.enter="searchList()"
    >
      <template v-if="!searchShow" #append>
        <div @click="goBack()" style="cursor: default">返回</div>
      </template>
    </el-input>
  </div>

  <div class="carousel" v-if="carouselShow">
    <el-carousel indicator-position="outside" height="500px">
      <el-carousel-item
        v-for="item in newsList"
        :key="item.id"
        @click="newsPreview(item)"
      >
        <el-image
          style="height: 500px"
          :src="`http://localhost:3000/${item.cover}`"
          fit="contain"
        />
      </el-carousel-item>
    </el-carousel>
  </div>

  <div class="grid-container" ref="scrollContainer">
    <worksList
      v-for="item in tableData"
      :item="item"
      v-show="searchShow"
      @click="handlePreview(item)"
    ></worksList>
    <worksList
      v-for="item in searchData"
      :item="item"
      v-show="!searchShow"
      @click="handlePreview(item)"
    ></worksList>
  </div>

  <div class="function">
    <a href="#"
      ><el-icon><Top /></el-icon
    ></a>
    <a href=""
      ><el-icon><Refresh /></el-icon
    ></a>
    <el-icon title="关闭广告栏" v-if="carouselShow" @click="carouselSwitch"
      ><Hide
    /></el-icon>
    <el-icon title="打开广告栏" v-else @click="carouselSwitch"><View /></el-icon>
  </div>

  <el-dialog
    style="border-radius: 10px; padding-bottom: 16px"
    v-model="dialogTableVisible"
    :destroy-on-close="true"
    v-if="dialogTableVisible"
    :show-close="false"
    width="60vw"
    top="10vh"
  >
    <div class="left">
      <el-carousel :autoplay="false" loop height="70vh">
        <el-carousel-item
          style="height: 100%"
          v-for="item in goodsFrom.imageList"
          :key="item"
        >
          <el-image
            :src="item"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="goodsFrom.imageList"
            :hide-on-click-modal="true"
            :preview-teleported="true"
            fit="contain"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="right">
      <div class="myData">
        <el-avatar
          :src="`http://localhost:3000${goodsFrom.avatar}`"
          @click="router.push(`/personal/${goodsFrom.username}`)"
        />
        <span style="font-size: 15px; font-weight: 600">{{ goodsFrom.name }}</span>
      </div>
      <p class="times">{{ time(goodsFrom.times) }}</p>
      <br />
      <pre class="pre">{{ goodsFrom.content }}</pre>
      <br />
      <el-divider content-position="right">评论区</el-divider>
      <div class="commentBox">
        <div class="commentList" v-if="commentList.length != 0">
          <div class="comment" v-for="item in commentList">
            <div class="myData">
              <el-avatar
                :src="`http://localhost:3000${item.avatar}`"
                :size="28"
                @click="router.push(`/personal/${item.username}`)"
              />
              <span>{{ item.name }}</span>
            </div>
            <p style="text-align: right; color: gray; font-size: 13px">
              {{ time(item.times) }}
            </p>
            <p>{{ item.comment }}</p>
          </div>
        </div>
      </div>
      <el-input
        class="commentInput"
        v-model="commentValue"
        style="width: 100%"
        placeholder="请输入评论..."
        @keyup.enter="commentPost"
      >
      </el-input>
    </div>
    <div style="clear: both"></div>

    <template #footer>
      <el-button
        type="primary"
        @click="createChat(goodsFrom.username, goodsFrom.name, goodsFrom.avatar)"
        v-if="store.state.userInfo.username != goodsFrom.username"
      >
        私信
      </el-button>
    </template>
  </el-dialog>

  <el-dialog class="previewBox" v-model="newsVisible" :fullscreen="true" title="新闻详情">
    <div>
      <el-image
        class="coverBox"
        :src="`http://localhost:3000${previewData.cover}`"
        fit="contain"
      />
      <br />
      <div>{{ previewData.title }}</div>
      <br />
      <div>{{ time(previewData.times) }}</div>
      <br />
      <hr />
      <div class="htmlContent" v-html="previewData.content"></div>
    </div>
  </el-dialog>
</template>
<style lang="scss" scoped>
.myData {
  display: flex;
  align-items: center;
  padding: 5px 0 5px 5px;
  span {
    padding-left: 7px;
    font-weight: 500;
  }
}
.search {
  margin: 0 auto;
  width: 50%;
  position: sticky;
  top: 0;
  border-radius: 50%;
  z-index: 11;
  .el-input {
    border-radius: 50%;
  }
}

.function {
  display: flex;
  flex-direction: column;
  position: absolute;
  bottom: 40px;
  right: 20px;

  .el-icon {
    width: 50px;
    height: 50px;
    background: rgba(65, 63, 63, 0.4);
    backdrop-filter: blur(10px);
    border-radius: 50%;
    color: white;
    font-size: 25px;
    margin-bottom: 10px;
  }
}

.dialog-right-button {
  position: absolute;
  right: 15px;
  bottom: 15px;
}

.grid-container {
  font-weight: 600;
  margin-top: 30px;
  column-count: 5;
  // column-width: 230px;
  column-gap: 15px;
  margin: 30px auto;
  .grid-content {
    box-sizing: border-box;
    overflow: hidden;
    margin-bottom: 10px;
    .img-box {
      border-radius: 15px;
      overflow: hidden;
    }
    .box-bottom {
      padding-left: 5px;
    }
    .box-content {
      width: 100%;
      height: 20px;
      line-height: 20px;
      white-space: normal;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 14px;
    }
  }
}

:deep(.el-image) {
  width: 100%;
  height: 100%;
}

.carousel {
  margin-top: 30px;
}
.el-carousel {
  position: relative;
}
.times {
  text-align: right;
}
.right {
  width: 40%;
  height: 70vh;
  float: right;
  display: flex;
  flex-direction: column;
  padding: 0 10px;
  position: relative;
  overflow: scroll;
  .commentBox {
    flex: 1;
    overflow: scroll;
    .comment {
      padding: 10px;
      line-height: 15px;
    }
  }
  .commentInput {
    position: sticky;
    bottom: 0;
  }
}
.left {
  width: 60%;
  height: 70vh;
  float: left;
}
:deep(.cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.pre {
  white-space: pre-wrap; /* 或者 pre，但 pre-wrap 会更合适 */
  word-wrap: break-word; /* 对于长单词或URL，确保它们也能换行 */
  overflow-wrap: break-word; /* 兼容性更好的替代方案 */
  font-family: "微软雅黑";
}

.previewBox {
  display: flex;
  justify-content: center;
  align-items: center;
  div {
    text-align: center;
  }
}
:deep(.htmlContent) {
  width: 80%;
  margin: 0 auto;
  img {
    max-width: 100%;
  }
}
.coverBox {
  width: 500px;
}
.el-carousel__item {
  text-align: center;
}
</style>
